const express = require("express");
const { db } = require("../database");

// const { validate, validators } = require("../validate");
// jwt
const { getPayloadByToken } = require("../jwt");
const { makePassword } = require("../utils");

// 创建路由对象，使得用户登录状态检查的中间件只作用于部分路由。
const router = express.Router();
// 创建用户登录状态检查的中间件
router.use(async (req, res, next) => {
  // 从请求头部获得 token
  const { token } = req.headers;
  const payload = getPayloadByToken(token);
  // 获取用户id
  const userId = payload?.userId || req.session?.userId;
  // 通过 session.userId 判断用户是否登录
  if (!userId) {
    return res.status(401).send({ success: false, message: "用户尚未登录!" });
  }
  // 为以后获取用户信息方便，将用户信息保存在 req.user 上。
  req.user = await db.findOne`select * from user where id = ${userId}`;
  next();
});
router
  /**
   * 用户注销
   */
  .get("/logout", (req, res) => {
    // 清除 session 信息
    req.session.destroy();
    res.send({
      success: true,
      message: "用户注销成功！",
    });
  })
  /**
   * 获取用户信息
   */
  .get("/user/info", async (req, res) => {
    res.send({
      success: true,
      user: req.user,
    });
  })
  /**
   * 新增员工
   */
  .post("/person", async (req, res) => {
    const person = req.body;
    // console.log(name);

    const id = await db.insert(
      "insert into person (name,sex,address,duty,phone,description,org) values (?,?,?,?,?,?,?)",
      [
        person.name,
        person.sex,
        person.address,
        person.duty,
        person.phone,
        person.description,
        person.org,
      ]
    );
    const results = await db.findOne`select * from person where id = ${id}`;
    res.send({
      code: 200,
      message: "员工新增成功",
      result: results,
    });
  })
  /**
   * 修改员工信息
   */
  .put("/person/info/:tid", async (req, res) => {
    // console.log("->", req.user.id);
    let person =
      await db.findOne`select * from person where id = ${req.params.tid}`;
    if (!person) {
      return res.send({ code: -1, message: "该员工信息不存在！" });
    }
    const { address, duty, phone, description, org } = req.body;
    // console.log(req.body);

    await db.run`update person set address = ${address},duty = ${duty},phone = ${phone},description = ${description},org = ${org} where id = ${req.params.tid}`;
    const persons =
      await db.findOne`select * from person where id = ${req.params.tid}`;
    res.send({
      code: 200,
      message: "用户信息修改成功",
      result: persons,
    });
  })
  /**
   * 所有员工信息
   */
  .get("/person/infos", async (req, res) => {
    const { offset = 0, limit = 1, role, state, department } = req.query;
    // console.log(req.query);
    const wheres = [],
      params = [];
    if (role != "all") {
      wheres.push("duty = ?");
      params.push(role);
    }
    if (state != "all") {
      wheres.push("description = ?");
      params.push(state);
    }
    if (department != "all") {
      wheres.push("org = ?");
      params.push(department);
    }
    // 执行查询 sql
    let sql = `select * from person where ${wheres.join(
      " and "
    )} limit ${offset},${limit}`;

    let sql2 = `select * from person where ${wheres.join(" and ")}`;


    if (role == "all" && state == "all" && department == "all") {
      sql = `select * from person limit ${offset},${limit}`;
      sql2 = `select * from person`;
    }
    const count = await db.select(sql2, params);
    let result = await db.select(sql, params);
    // console.log(limit);
    res.send({
      code: 200,
      message: "用户查找成功",
      result: {
        offset,
        limit,
        result,
        count: count.length,
        page: offset / limit + 1,
      },
    });
  })
  /**
   * 查找员工信息
   */
  .get("/person/info", async (req, res) => {
    const { name } = req.query,
      likeName = `%${name}%`;
    // console.log(req.query, name,`select * from person where name like ${likeName}`);
    let result =
      await db.select`select * from person where name like ${likeName}`;
    // console.log(result);
    res.send({
      code: 200,
      message: "用户查找成功",
      result,
    });
  })
 
 // * 获取任务
router.get("/tasks", async (req, res) => {
  const {
      days = "all",
      task = "all",
      limit = 3,
      offset = 0,
  } = req.query;
  const wheres = [" personId= ?"],
      params = [req.user.id];
  if (days != "all") {
      wheres.push(
          `found_time between date_add(now(), interval - ${days} day) and now()`
      );
  }
  if (task != "all") {
      wheres.push("status = ?");
      params.push(task);
  }
  // 获取查询的总数
  let sql = `select count(*) as count from task`;
  const { count } = await db.findOne(sql, params);
  // 执行查询 sql
  sql = `select * from task`;
  const results = await db.select(sql, params);
  res.send({
      code: 200,
      message: "获取任务成功",
      result: {
          count,
          limit,
          offset,
          page: offset / limit + 1,
          task,
          results
      }
  });
});
// * 新增任务
router.post("/task", async (req, res) => {
  const { title, content } = req.body;
  const id = await db.insert("INSERT INTO task ( personId, title, content) VALUES (?,?,?)", [req.user.id, title, content])
  const task = await db.findOne`select * from task where id=${id}`
  res.send({
      code: 200,
      message: "添加成功",
      result: task
  })
})
// * 删除任务
router.delete("/task/:id", async (req, res) => {
  let task = await db.findOne`select * from task where id = ${req.params.id}`
  if (!task) {
      return res.send({ code: -1, message: "该任务信息不存在！" });
  }
  await db.run`DELETE FROM task WHERE id=${req.params.id}`
  res.send({
      code: 200,
      message: "删除成功"
  })
})
// * 修改任务
router.put("/task/:id", async (req, res) => {
  let task =
      await db.findOne`select * from task where id = ${req.params.id} and personId = ${req.user.id}`;
  if (!task) {
      return res.send({ code: -1, message: "该任务信息不存在！" });
  }
  if (task.finish_time) {
      return res.send({
          code: -1,
          message: "该任务已经完成，不能修改！",
      });
  }
  const { title, content } = req.body;
  await db.run`update task set title = ${title}, content = ${content} where id = ${req.params.id}`;
  task = await db.findOne`select * from task where id = ${req.params.id}`;
  res.send({
      code: 200,
      result: task
  })
})

// * 完成任务
router.put("/task/finish/:id", async (req, res) => {
  let task =
      await db.findOne`select * from task where id = ${req.params.id}`;
  if (!task) {
      return res.send({ code: -1, message: "该任务信息不存在！" });
  }
  if (task.finish_time) {
      return res.send({
          code: -1,
          message: "该任务已经完成，不需再次完成！",
      });
  }
  await db.run(
      "update task set finish_time = current_timestamp where id = ?",
      [req.params.id]
  );
  task = await db.findOne("select * from task where id = ?", [
      req.params.id,
  ]);
  res.send({
      code: 200,
      result: task
  })
})
// .get("/task/stat", async (req, res) => {
//   const { id } = req.user,
//     { count } = await db.findOne(
//       "select count(*) as count from task where id = ?",
//       [id]
//     ),
//     finished = await db.select(
//       `select count(*) as count from task 
//         where id = ? and found_time is not null`,
//       [id]
//     ),
//     notFinished = await db.select(
//       `select count(*) as count from task
//         where id = ? and found_time is null`,
//       [id]
//     );
//   res.send({
//     success: true,
//     stat: {
//       count,
//       finished,
//       notFinished,
//     },
//   });
// })
// * 获取便签
router.get("/memo", async (req, res) => {
  const {
      days = "all",
      memo = "all",
      limit = 10,
      offset = 0,
  } = req.query;
  const wheres = [" personId= ?"],
      params = [req.user.id];
  if (days != "all") {
      wheres.push(
          `found_time between date_add(now(), interval - ${days} day) and now()`
      );
  }
  if (memo != "all") {
      wheres.push("status = ?");
      params.push(memo);
  }
  // 获取查询的总数
  let sql = `select count(*) as count from memo`;
  const { count } = await db.findOne(sql, params);
  // 执行查询 sql
  sql = `select * from memo`;
  const results = await db.select(sql, params);
  res.send({
      code: 200,
      message: "获取任务成功",
      result: {
          count,
          limit,
          offset,
          page: offset / limit + 1,
          memo,
          results
      }
  });
})
// * 新增便签
router.post("/memo", async (req, res) => {
  const { title, content } = req.body;
  const id = await db.insert("INSERT INTO memo ( personId, title, content,status) VALUES (?,?,?,?)", [req.user.id, title, content,'0'])
  const memo = await db.findOne`select * from memo where id=${id}`
  const { count } = await db.findOne(`SELECT COUNT(*) AS count FROM memo WHERE personId=?`,[req.user.id])
  res.send({
      code: 200,
      message: "添加成功",
      result: memo,
      count,
  })
})
// * 删除便签
router.delete("/memo/:id", async (req, res) => {
  let memo = await db.findOne`select * from memo where id = ${req.params.id}`
  if (!memo) {
      return res.send({ code: -1, message: "该任务信息不存在！" });
  }
  const id =  await db.run`DELETE FROM memo WHERE id=${req.params.id}`
  res.send({
      code: 200,
      message: "删除成功"
  })
})
// * 修改便签
router.put("/memo/:id", async (req, res) => {
  let memo =
      await db.findOne`select * from memo where id = ${req.params.id} and personId = ${req.user.id}`;
  if (!memo) {
      return res.send({ code: -1, message: "该任务信息不存在！" });
  }
  if (memo.finish_time) {
      return res.send({
          code: -1,
          message: "该任务已经完成，不能修改！",
      });
  }
  const { title, content } = req.body;
  await db.run`update memo set title = ${title}, content = ${content} where id = ${req.params.id}`;
  memo = await db.findOne`select * from memo where id = ${req.params.id}`;
  res.send({
      code: 200,
      result: memo
  })
})

// * 完成便签
router.put("/memo/finish/:id", async (req, res) => {
  let memo =
      await db.findOne`select * from memo where id = ${req.params.id}`;
  if (!memo) {
      return res.send({ code: -1, message: "该便签信息不存在！" });
  }
  if (memo.finish_time) {
      return res.send({
          code: -1,
          message: "该便签已经完成，不需再次完成！",
      });
  }
  await db.run(
      "update memo set finish_time = current_timestamp where id = ?",
      [req.params.id]
  );
  memo = await db.findOne("select * from memo where id = ?", [
      req.params.id,
  ]);
  res.send({
      code: 200,
      result: memo
  })
})
// 将路由作为中间件挂接在 / 根路由上。
const registerRouter = (app) => app.use("/", router);

module.exports = { registerRouter };
